package com.yimu.lib.util;

import android.util.Log;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


/**
 * 描述： MD5工具类
 * 创建者：  Churck
 * 创建时间：16/6/8 13:54
 * 修改者： Churck
 * 修改时间：16/6/8 13:54
 * 版 本：v1.0
 */
public class MD5Utils {

	private static final char[] hexChars = "0123456789abcdef".toCharArray();

	/**
	 * 字节数组转16进制字符串
	 * @param data 字节数组
	 * @return 6进制字符串
	 */
	public static String toHex(byte[] data) {
		if (data == null) return null;
		StringBuilder sb = new StringBuilder(data.length << 2);
		for (byte b : data) {
			sb.append(hexChars[(b & 0xFF) >> 4]);
			sb.append(hexChars[b & 0xF]);
		}
		return sb.toString();
	}

	/**
	 * 16进制字符串转字节数组
	 * @param hex 16进制字符串
	 * @return 节数组
	 */
	public static byte[] fromHex(String hex) {
		if (hex == null) return null;
		int len = hex.length();
		if (len == 0) return new byte[0];
		if (len % 2 == 1) {
			hex = "0" + hex;
			len++;
		}
		ByteArrayOutputStream out = new ByteArrayOutputStream(len / 2);
		for (int i = 0; i < len; i += 2) {
			out.write(Integer.parseInt(hex.substring(i, i + 2), 16));
		}
		return out.toByteArray();
	}

	public static String toMD5(byte[] data) {
		try {
			return toHex(MessageDigest.getInstance("MD5").digest(data));
		} catch (NoSuchAlgorithmException e) {
			return null;
		}
	}

	public static String toMD5(File file) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			InputStream in = new BufferedInputStream(new FileInputStream(file));
			byte[] buf = new byte[1024];
			int count;
			while ((count = in.read(buf)) > -1) {
				md.update(buf, 0, count);
			}
			in.close();
			return toHex(md.digest());
		} catch (Exception e) {
			return null;
		}
	}

	public static boolean checkMD5(File file, String md5) {
		return md5.equalsIgnoreCase(toMD5(file));
	}

	public static String toSHA1(byte[] data) {
		MessageDigest md;
		try {
			md = MessageDigest.getInstance("SHA-1");
		} catch (NoSuchAlgorithmException e) {
			MyLogger.e(e.toString());
			return toHex(data);
		}
		return toHex(md.digest(data));
	}

	public static String toSHA1(String str) {
		if (TextUtils.isEmpty(str)) return "";
		byte[] b;
		try {
			b = str.getBytes("UTF-8");
		} catch (Exception e) {
			b = str.getBytes();
		}
		return toSHA1(b);
	}

	public static byte[] readFully(InputStream is) throws IOException {
		BufferedInputStream in = null;
		if (is instanceof BufferedInputStream) {
			in = (BufferedInputStream) is;
		} else {
			in = new BufferedInputStream(is);
		}
		byte[] buf = new byte[1024];
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int len;
		while ((len = in.read(buf)) > -1) {
			baos.write(buf, 0, len);
		}
		in.close();
		return baos.toByteArray();
	}

}
